using System.Data;
using System.Web.Security;
using StillVoiceCommon;
using System;
using TeamTime.Classes;
using System.Collections.Generic;
namespace TeamTime
{

    partial class Login : System.Web.UI.Page
    {

        Security Security1 = new Security(StillVoiceCommon.sqlDB.getDBConnString());
        // string redirectTo;
        #region " Web Form Designer Generated Code "

        //This call is required by the Web Form Designer. 
        [System.Diagnostics.DebuggerStepThrough()]
        private void InitializeComponent()
        {

        }


        private void Page_Init(object sender, System.EventArgs e)
        {
            //CODEGEN: This method call is required by the Web Form Designer 
            //Do not modify it using the code editor. 
            InitializeComponent();
        }

        #endregion

        private void Page_Load(object sender, System.EventArgs e)
        {
            //Put user code to initialize the page here 
            //If Not Page.IsPostBack Then 
            // redirectTo = "default.aspx" 
            // If Not Request.UrlReferrer Is Nothing Then 
            // If Request.UrlReferrer.ToString() > "" Then 
            // redirectTo = Request.UrlReferrer.ToString() 
            // End If 
            // End If 
            //End If 
            if (!Page.IsPostBack)
            {
                //this.Form.DefaultFocus = this.LoginCode.ClientID;
                //this.Form.DefaultButton = this.btnLogin.UniqueID;
            }
        }

        protected void btnLogin_Click(object sender, System.EventArgs e)
        {
            DataSet ds;

            if (Page.IsValid)
            {
                Security1.initClass(sqlDB.getDBConnString());
                ds = Security1.LoginUser(LoginCode.Text, Password.Text);
                if (ds.Tables[0].Rows.Count > 0)
                {
                    Int32 UserID = Convert.ToInt32(ds.Tables[0].Rows[0]["ID"]);
                    //user found - correct user details supplied 
                    User user = new User(UserID);
                    user.load(UserID);
                    Session["UserID"] = user.Fields["ID"];
                    Session["UserName"] = user.Fields["Firstname"] + " " + user.Fields["LastName"];
                    Session["DefaultUserGroupID"] = user.Fields["DefaultUserGroupID"];
                    
                    if (user.Fields["PersonID"] != DBNull.Value)
                    {
                        
                        Person person = new Person();
                        person.load(Convert.ToInt32( user.Fields["PersonID"]));
                        List<Company> listCompanies= person.GetCompanies();
                        if (listCompanies.Count == 1) //Person linked to multi companies
                        {
                            Session["CompanyID"] = listCompanies[0].KeyValue;
                        }
                        else
                        {
                            Session["CompanyID"] = listCompanies[0].KeyValue;
                           
                            
                            //this.pnlCompanies.Visible = true;
                            // TODO:  Multi companies panel
                        }
                        Companies companies = new Companies();
                        Session["CompanyName"] = companies.getCompanyNameByID(Convert.ToInt32(Session["CompanyID"]));
                    }
                    else
                    { //TODO: handle the no employee record case
                    }
                    
                    FormsAuthentication.SetAuthCookie(Session["UserID"].ToString(), true);
                    if (Password.Text.ToLower() == "password")
                    {
                        //user must be forced to supply a new password, this would have happened in the case of a password reset by the administrator 
                        lblMsg.Text = "You have been logged in as " + Session["UserName"] + ", however you must change your password before continuing.";
                        this.trp0.Visible=true;
                        this.trp1.Visible = true;
                        this.trp2.Visible = true;
                        this.trp3.Visible = true;
                        this.trp4.Visible = true;
                        this.LoginCode.Enabled = false;
                        this.Password.Enabled = false;
                        this.Requiredfieldvalidator1.Enabled = false;
                        this.Requiredfieldvalidator2.Enabled = false;
                        this.btnLogin.Visible = false;
                       // this.pnlLoginForm.Visible = false;
                    }
                    else
                    {
                        this.lblMsg.Text = "";
                        nextPage();
                    }
                }

                else
                {
                    lblMsg.Text = "Invalid Credentials: Please try again";
                }
            }
            else
            {
                lblMsg.Text = "Invalid Credentials: Please try again";
            }
        }
        private void nextPage()
        {
            //TODO:Go next - handle case when Admin can do multi-Employees
            if (Request.QueryString["url"] == null)
            {
                Response.Redirect("default.aspx");
            }
            else
            {
                Response.Redirect(Request.QueryString["url"]);
            }
        }
        protected void btnSave_Click(object sender, System.EventArgs e)
        {
            StillVoiceCommon.User u = new StillVoiceCommon.User(Convert.ToInt32(Session["UserID"]));
            u.load(Session["UserID"].ToString(), "ID", false);
            u.updatePassword(this.txtPassword1.Text);
            nextPage();
        }

        protected void lnkForgotPassword_Click(object sender, EventArgs e)
        {
            if (this.LoginCode.Text == "")
            {
                this.Requiredfieldvalidator1.Enabled = true;
                this.Requiredfieldvalidator1.Enabled = false;
            }
            else
            {
                User user = new User();
                try
                {
                    user.loadByLoginCode(this.LoginCode.Text);
                    user.sendPasswordEmail(Request.ServerVariables["SERVER_NAME"], Request.ServerVariables["SERVER_PORT"]);
                    this.lblMsg.Text = "A password reminder email has been sent to your email address.";
                }
                catch (Exception ex)
                {
                    this.lblMsg.Text = ex.Message;
                }

            }
        }
    }

}